package com.meilai.project.controller.web.business.intentionScheme;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.meilai.project.controller.mini.dto.MiniCustomerNeedSearchParams;
import com.meilai.project.controller.mini.vo.MiniCustomerNeedVO;
import com.meilai.project.dto.base.ApiResult;
import com.meilai.project.dto.business.intentionScheme.*;
import com.meilai.project.entity.business.sale.BillSale;
import com.meilai.project.service.business.installOrder.WorkOrderService;
import com.meilai.project.service.business.intentionScheme.IntentionSchemeService;
import com.meilai.project.service.business.intentionScheme.PointProcessService;
import com.meilai.project.service.business.sale.BillSaleService;
import com.meilai.project.vo.business.intentionScheme.IntentionSchemeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xchen
 * @since 2022-02-20
 */
@Api(value = "意向方案controller", tags = "意向方案")
@RequestMapping("api/web/intention_scheme")
@RestController
@Validated
public class IntentionSchemeController {

    @Autowired
    private IntentionSchemeService service;

    @Autowired
    private PointProcessService processService;

    @Autowired
    private BillSaleService billSaleService;

    @Autowired
    private WorkOrderService workOrderService;

	/*@GetMapping("combo_info")
	@ApiOperation("套餐信息")
	public ApiResult<List<ComboVO>> comboInfo() {
		return ApiResult.ok(processService.getComboCountList());
	}*/

    @GetMapping("export_point_detail")
    @ApiOperation(value = "导出详细点位")
    public void exportPointDetail(HttpServletResponse response, @RequestParam(value = "id") Long id, @RequestParam(value = "name") String name) {
        workOrderService.exportLockPointDetail(id, name, response);
    }

    @PostMapping("search")
    @ApiOperation("筛选")
    public ApiResult<List<BuildingPointVO>> search(@RequestBody PointProcessSearchDTO searchDTO) {
        List<BuildingPointVO> result = service.search(searchDTO);
        return ApiResult.ok(result);
    }

    @PostMapping("searchAll")
    @ApiOperation("筛选")
    public ApiResult<List<BuildingPointVO>> searchAll(@RequestBody PointProcessSearchDTO searchDTO) {
        List<BuildingPointVO> result = service.searchAll(searchDTO);
        return ApiResult.ok(result);
    }

    @GetMapping("list-by-related")
    @ApiOperation("查询关联的锁位列表（合同或者销售单）")
    public ApiResult<List<IntentionSchemeVO>> listByRelated(
            Long related_id, Integer related_type, Long must_include_id, Integer type) {
        List<IntentionSchemeVO> intentionSchemeVOS = service.listByRelated(related_id, related_type, must_include_id, type);
        return ApiResult.ok(intentionSchemeVOS);
    }

    //已作废
    @Deprecated
    @GetMapping("list-all-by-related-type")
    @ApiOperation("根据类型查询锁位列表（合同或者销售单）")
    public ApiResult<List<IntentionSchemeVO>> listAllByRelatedType(
            @ApiParam(value = "1:合同，2:销售单") Integer related_type) {
        List<IntentionSchemeVO> intentionSchemeVOS = service.listAllByRelatedType(related_type);
        return ApiResult.ok(intentionSchemeVOS);
    }


    @GetMapping("list")
    @ApiOperation(value = "列表分页")
    public ApiResult<Page<IntentionSchemeVO>> list(@ApiParam("form") IntentionSchemeListDTO req) {
        Page<IntentionSchemeVO> regularApplyVOPage = service.selectPageList(req);
        processBillSaleStatus(regularApplyVOPage.getRecords());
        return ApiResult.ok(regularApplyVOPage);
    }

    //已作废
    @Deprecated
    @GetMapping("list-by-contract-id")
    @ApiOperation(value = "列表分页")
    public ApiResult<List<IntentionSchemeVO>> listByContractId(Long contractId) {
        List<IntentionSchemeVO> regularApplyVOPage = service.listByContractId(contractId);
        return ApiResult.ok(regularApplyVOPage);
    }

    private void processBillSaleStatus(List<IntentionSchemeVO> intentionSchemeVOList) {
        if (CollUtil.isEmpty(intentionSchemeVOList)) {
            return;
        }
        List<Long> chooseIds = intentionSchemeVOList.stream().map(IntentionSchemeVO::getChoose_id)
                .distinct().collect(Collectors.toList());
        List<BillSale> billSaleList = billSaleService.listByChooseIds(chooseIds);
        Map<Long, BillSale> billSaleMap = billSaleList.stream().collect(Collectors.toMap(BillSale::getIntention_scheme_id, Function.identity()));
        for (IntentionSchemeVO intentionSchemeVO : intentionSchemeVOList) {
            BillSale billSale = billSaleMap.get(intentionSchemeVO.getId());
            if (null != billSale) {
                intentionSchemeVO.setBillSaleStatus(billSale.getFlow_status());
            }
        }
    }

    @GetMapping("export")
    @ApiOperation("导出")
    public void export(HttpServletResponse response, @ApiParam("form") IntentionSchemeListDTO req) {
        service.exportExcel(response, req);
    }

    @GetMapping("detail")
    @ApiOperation(value = "单据明细")
    public ApiResult<IntentionSchemeVO> detail(
            @ApiParam("id") @RequestParam(value = "id", required = false) Long id
    ) {
        return ApiResult.ok(service.getOneById(id));
    }

    @PostMapping("save")
    @ApiOperation("保存")
    public ApiResult<IntentionSchemeSaveDTO> save(@ApiParam("json") @Validated @RequestBody IntentionSchemeSaveDTO req) {
        try {
            return service.save(req);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("保存失败，请联系管理员！");
        }
    }

    @PutMapping("link-contract")
    @ApiOperation("关联合同")
    public ApiResult<Boolean> linkContract(@ApiParam("json") @RequestBody @Validated IntentionSchemeLinkContractDTO req) {
        try {
            return service.linkContract(req);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("关联失败，请联系管理员！");
        }
    }

    @PostMapping("unlink-contract")
    @ApiOperation("解除关联合同")
    public ApiResult<Boolean> linkContract(@ApiParam("id") Long id) {
        try {
            return service.unlinkContract(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("解除关联失败，请联系管理员！");
        }
    }

    @PutMapping("lock")
    @ApiOperation("保存并锁定")
    public ApiResult<IntentionSchemeSaveDTO> lock(@ApiParam("json") @RequestBody IntentionSchemeSaveDTO req) {
        try {
            return service.lock(req);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("保存并锁定失败，请联系管理员！");
        }
    }

    @PutMapping("lock-by-id")
    @ApiOperation("通过id锁定")
    public ApiResult<IntentionSchemeSaveDTO> lockById(@ApiParam("id") @RequestParam("id") Long id) {
        IntentionSchemeVO intentionSchemeVO = service.getOneById(id);
        if (null == intentionSchemeVO) {
            return ApiResult.err("方案不存在！");
        }
        try {
            IntentionSchemeSaveDTO schemeSaveDTO = intentionSchemeVO.to();
            return service.lock(schemeSaveDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("锁定失败，请联系管理员！");
        }
    }


    @PostMapping("check-date-range-lock")
    @ApiOperation("检查不同的时间段内是否有点位冲突")
    public ApiResult<PointProcessLockedMediaPointDTO> checkDateRangeLock(@ApiParam("json") @RequestBody IntentionSchemeSaveDTO req) {
        try {
            return service.checkDateRangeLock(req);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("系统异常！请联系管理员");
        }
    }

    @PostMapping("release")
    @ApiOperation("释放锁定")
    public ApiResult<Boolean> release(@ApiParam("id") Long id) {
        try {
            Boolean release = service.release(id);
            return ApiResult.ok(release);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("释放锁定失败！请联系管理员");
        }
    }

    @PostMapping("delete")
    @ApiOperation("删除")
    public ApiResult<Boolean> delete(@ApiParam("id") Long id) {
        try {
            Boolean release = service.delete(id);
            return ApiResult.ok(release);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("删除失败！请联系管理员");
        }
    }

    @PostMapping("push_msg")
    @ApiOperation("向客户维护人，推送锁位完成的消息")
    public ApiResult<Boolean> pushMSG(@ApiParam("id") Long id) {
        try {
            return ApiResult.ok(service.pushMSG(id));
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("推送失败！请联系管理员");
        }
    }

    @GetMapping("/needSelectPage")
    @ApiOperation("查询小程序客户意向方案")
    public ApiResult<Page<MiniCustomerNeedVO>> needSelectPage(MiniCustomerNeedSearchParams params) {
        try {
            return ApiResult.ok(service.needSelectPage(params));
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err("查询失败！请联系管理员");
        }
    }
}
